﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Models;
using ConcreteService;
using Newtonsoft.Json.Linq;
using Infrastructures;

namespace SponsorshipWeb.Controllers
{
    public class AdminController : ApiController
    {
        StudentService studentService = ServiceFactory.CreateInstance<StudentService>();
        CompanyService companyService = ServiceFactory.CreateInstance<CompanyService>();
        ProjectService projectService = ServiceFactory.CreateInstance<ProjectService>();
        UtilService utilService = ServiceFactory.CreateInstance<UtilService>();
        AssociationService assoService = ServiceFactory.CreateInstance<AssociationService>();
        AdminService service = ServiceFactory.CreateInstance<AdminService>();
        UserInfoService uService = ServiceFactory.CreateInstance<UserInfoService>();
        UserValidationService lservice = ServiceFactory.CreateInstance<UserValidationService>();


        [HttpPost]
        public IHttpActionResult ListStudent([FromBody]JObject value)
        {
            var user = AuthUtil.GetAuthentication();

            var json = service.ListStudent( GetIntValue(value, "Start"), GetIntValue(value, "Limit"));

            return Ok(new JsonResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseJson = json
            });
        }

        public IHttpActionResult GetStudentInfo(int userID)
        {
            var userinfo = uService.Get<UserInfo>(userID.ToString());
            var asso = assoService.GetAssociationByUserID(userID);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (asso != null)
            {
                dic = asso.ToDictionary();
                dic.Add("SchoolName", asso.School.SchoolName);
            }

            dic.AddOrReplace("Status", userinfo.Status.ToString());
            dic.AddOrReplace("LogoPath", SystemConfig.Get("UploadHttpPath") + userinfo.HeadImage);
            
            var student = service.Get<Student>(userID.ToString());
            if (student != null)
            {
                dic.Add("StudentName", student.Name);
                dic.Add("Major", student.Major);
                dic.Add("Education", student.Education);
                dic.Add("StudentLDNO", student.StudentLDNO);
                dic.Add("EnterYear", student.EntranceDate.Year.ToString());
            }
            dic.Add("Phone", userinfo.Phone);
            dic.Add("QQ", userinfo.QQ);
            dic.Add("WeChart", userinfo.WeChart);
            dic.Add("Email", userinfo.Email);
            var lstse = utilService.ListSeldomUsed(userID, SeldomType.All, APPRole.Student);
            if (lstse == null || lstse.Count() == 0)
            {
                lstse = utilService.ListSeldomUsed(userID, SeldomType.All, APPRole.Company);
            }
            var existSe1 = lstse.Where(x => x.Type == SeldomType.PersonCardNo).FirstOrDefault();
            var existSe2 = lstse.Where(x =>x.Type == SeldomType.AliPayNo).FirstOrDefault();
            var existSe3 = lstse.Where(x => x.Type == SeldomType.BankNo).FirstOrDefault();
            if (existSe1 != null)
            {
                dic.Add("PersonCardNo", existSe1.Value);
            }
            if (existSe2 != null)
            {
                dic.Add("AliPayNo", existSe2.Value);
            }
            if (existSe3 != null)
            {
                dic.Add("BankNo", existSe3.Value);
            }
            FileSystem stuIDCardContent = utilService.ListFileSystem(FileType.StuIDCardContent, userID).FirstOrDefault();
            FileSystem stuIDCardCover = utilService.ListFileSystem(FileType.StuIDCardCover, userID).FirstOrDefault();
            if (stuIDCardContent != null)
            {
                dic.Add("StuIDCardContent",stuIDCardContent.Path);
            }
            if (stuIDCardCover != null)
            {
                dic.Add("StuIDCardCover", stuIDCardCover.Path);
            }


            return Ok(new DictResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseDict = dic
            });
        }

        [HttpGet]
        public IHttpActionResult CompanyAudit()
        {
            //IList<Company> lst = null; //companyService.ListCompanyByStatus(CommonStatus.Pending);
            //return Ok(new ListResponse()
            //{
            //    Status = ResponseStatus.OK(),
            //    ResponseList = lst.Select(x => (Object)x).ToList()
            //});
            return null;
        }

        [HttpGet]
        public void UpdateStatus([FromUri]string type, [FromUri]string id, [FromUri]string roleType)
        {
            var userInfo = uService.Get<UserInfo>(id.ToString());
            if (type == "ok")
            {
                userInfo.Status = CommonStatus.Verified;
                uService.Update(userInfo, id.ToString());
                UserValidation val = new UserValidation();
                val.AccountValue = userInfo.UserName;
                val.AccountType = AccountType.Phone;
                val.ValidType = ValiationType.Verified;
                val.CreatedTime = DateTime.Now;

                lservice.SendValidationMessage(val);
            }
            else
            {
                userInfo.Status = CommonStatus.Rejected;
                uService.Update(userInfo, id.ToString());
                UserValidation val = new UserValidation();
                val.AccountValue = userInfo.UserName;
                val.AccountType = AccountType.Phone;
                val.ValidType = ValiationType.FiveStep;
                val.CreatedTime = DateTime.Now;

                lservice.SendValidationMessage(val);
            }
        }

        [HttpGet]
        public IHttpActionResult CompanyBook()
        {
            IList<Project> lst = null; //projectService.ListProjectByStatus(APPRole.Company, ProjectStatus.Draft);
            return Ok(new ListResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseList = lst.Select(x => (Object)x).ToList()
            });
        }


        [HttpGet]
        public IHttpActionResult AssoBook()
        {
            IList<Project> lst = null; //projectService.ListProjectByStatus(APPRole.Student, ProjectStatus.Draft);
            return Ok(new ListResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseList = lst.Select(x => (Object)x).ToList()
            });
        }

        [HttpGet]
        public IHttpActionResult AssoInfo()
        {
            IList<Association> lst = null; //assoService.ListByStatus(CommonStatus.Pending);
            return Ok(new ListResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseList = lst.Select(x => (Object)x).ToList()
            });
        }

         [HttpGet]
        public IHttpActionResult StudentInfo()
        {
            IList<Student> lst = null; //studentService.ListStudentByStatus(CommonStatus.Pending);
            return Ok(new ListResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseList = lst.Select(x => (Object)x).ToList()
            });
        }

         private string GetValue(JObject value, Enum name)
         {
             if (value == null)
                 return string.Empty;

             return value[name.ToString()] == null ? string.Empty : value[name.ToString()].ToString();
         }

         private string GetValue(JObject value, string name)
         {
             if (value == null)
                 return string.Empty;

             return value[name] == null ? string.Empty : value[name].ToString();
         }

         private int GetIntValue(JObject value, Enum name)
         {
             if (value == null)
                 return 0;

             return value[name.ToString()] == null ? 0 : value[name.ToString()].ToString().ToInt();
         }

         private int GetIntValue(JObject value, string name)
         {
             if (value == null)
                 return 0;

             return value[name] == null ? 0 : value[name].ToString().ToInt();
         }
    }
}